<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.name" placeholder="权限名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table border :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selectChange"
              style="width: 100%;">
      <el-table-column type="selection">
      </el-table-column>
      <el-table-column type="index">
      </el-table-column>
      <el-table-column prop="name" label="角色名称">
      </el-table-column>
      <el-table-column prop="sn" label="角色sn">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.selection.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>
    <el-dialog :title="title" :visible.sync="dialogVisible" @close="dialogClose" width="30%">
      <el-form :model="role" label-width="80px" :rules="rules" ref="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="role.name"></el-input>
        </el-form-item>
        <el-form-item label="sn">
          <el-input v-model="role.sn"></el-input>
        </el-form-item>
        <el-form-item label="权限分配">
          <el-tree
              :data="permissionTree"
              show-checkbox
              node-key="id"
              accordion
              ref="tree"
              highlight-current
              :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item label="菜单分配">
          <el-tree
              :data="menuTree"
              show-checkbox
              node-key="id"
              accordion
              ref="tree2"
              highlight-current
              :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogClose">取消</el-button>
          <el-button type="primary" @click="submit" :loading="saveLoading">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </section>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      query: {},
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      listLoading: false,
      selection: [],
      dialogVisible: false,
      title: '',
      role: {},
      rules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ]
      },
      saveLoading: false,
      permissionTree: [],
      menuTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  mounted() {
    this.getRoleList();
  },
  methods: {
    batchRemove() {
      this.$axios.patch('/role', this.selection)
          .then(res => {
            if (res.data.code === 1) {
              this.$message.success("删除成功!");
              this.getRoleList();
            } else {
              this.$message.error(res.data.msg || '删除失败');
            }
          })
    },
    getPermissionTree() {
      this.$axios.get('/permission/tree')
          .then(res => {
            if (res.data.code === 1) {
              this.permissionTree = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
    },
    getMenuTree() {
      this.$axios.get('/menu/tree')
          .then(res => {
            if (res.data.code === 1) {
              this.menuTree = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
    },
    search() {
      this.currentPage = 1;
      this.getRoleList();
    },
    getRoleList() {
      this.$axios.post('/role', {
        name: this.query.name,
        page: this.currentPage,
        pageSize: this.pageSize
      }).then(res => {
        if (res.data.code === 1) {
          this.tableData = res.data.data.rows;
          this.total = res.data.data.total;
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    add() {
      this.title = '新增角色';
      this.dialogVisible = true;
      this.getPermissionTree();
      this.getMenuTree();
    },
    submit() {
      this.$refs.rules.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {type: 'warning'}).then(() => {
            this.saveLoading = true;
            // 将选择的菜单的父级节点选中
            let data = {
              role: this.role,
              permissionIds: this.$refs.tree.getCheckedKeys(),
              menuIds: this.$refs.tree2.getCheckedKeys().concat(this.$refs.tree2.getHalfCheckedKeys())
            }
            this.$axios.put('/role/saveOrUpdate', data).then((res) => {
              this.saveLoading = false;
              if (res.data.code === 1) {
                this.$message.success("提交成功")
              } else {
                this.$message.error(res.data.msg || '提交失败');
              }
              this.$refs['rules'].resetFields();
              this.dialogVisible = false;
              this.getRoleList();
            });
          });
        }
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getRoleList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getRoleList();
    },
    selectChange(val) {
      this.selection = val.map(item => item.id);
    },
    dialogClose() {
      this.role = {};
      this.dialogVisible = false;
      // 清空tree
      this.$refs.tree.setCheckedKeys([]);
      this.$refs.tree2.setCheckedKeys([]);
    },
    handleEdit(row) {
      // 查询拥有的权限ID
      this.$axios.get('/role/permission/' + row.id)
          .then(res => {
            if (res.data.code === 1) {
              this.getPermissionTree();
              this.$nextTick(() => {
                this.$refs.tree.setCheckedKeys(res.data.data);
              })
            } else {
              this.$message.error(res.data.msg);
            }
          })
      // 查询拥有的菜单ID
      this.$axios.get('/role/menu/' + row.id)
          .then(res => {
            if (res.data.code === 1) {
              this.getMenuTree();
              this.$nextTick(() => {
                console.log(res.data.data)
                // 查看每条数据的parentId是否为null, 为null则剔除, 并返回每条数据的id集合
                let list = res.data.data.filter(item => item.parentId !== null).map(item => item.id);
                this.$refs.tree2.setCheckedKeys(list);
              })
            } else {
              this.$message.error(res.data.msg);
            }
          })
      this.title = '编辑角色';
      this.dialogVisible = true;
      this.role = {...row};
    },
    handleDel(id) {
      this.$confirm('确认删除该记录吗？', '提示', {type: 'warning'}).then(() => {
        this.listLoading = true;
        this.$axios.delete('/role/' + id).then((res) => {
          this.listLoading = false;
          if (res.data.code === 1) {
            this.$message.success("删除成功")
            //如果当前页数据被删除完了，则自动切换到上一页
            if (this.tableData.length === 1 && this.currentPage > 1) {
              this.currentPage--;
            }
            this.getRoleList();
          } else {
            this.$message.error(res.data.msg || '删除失败');
          }
        })
      })
    }
  }
}
</script>

<style scoped>

</style>